/*
 * Copyright 2020-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jljiayu.config.security;

import cn.jljiayu.core.api.APIResponse;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import java.io.PrintWriter;

/**
 * @author Joe Grandja
 * @since 0.1.0
 */
@EnableWebSecurity
public class DefaultSecurityConfig {

	@Autowired
	private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

	// @formatter:off
	@Bean
	SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
		http
			.formLogin().loginPage("/login")
			.successHandler(customAuthenticationSuccessHandler)
			.failureHandler(authenticationFailureHandler()).permitAll()
			.and().logout().logoutUrl("/api/system/user/logout").logoutSuccessHandler(logoutSuccessHandler())
			.and().csrf().ignoringAntMatchers("/api/system/user/logout")
			.and()
			.authorizeRequests(authorizeRequests ->
					authorizeRequests.antMatchers("/favicon.ico","/static/**").permitAll()
			)
			.authorizeRequests(authorizeRequests ->
					authorizeRequests.anyRequest().authenticated()
			)
			.rememberMe()// 记住我相关配置
			.rememberMeCookieName("spring-security-oauth-remember-me")
			.tokenRepository(new InMemoryTokenRepositoryImpl())
			.tokenValiditySeconds(7*24*60*60)
			.userDetailsService(userDetailsService());
		http.authenticationProvider(loginPwdDaoAuthenticationProvider());
		http.headers().frameOptions().disable();
		return http.build();
	}
	// @formatter:on

	// @formatter:off
	@Bean
	UserDetailsService userDetailsService() {
		UserDetails user = User.withDefaultPasswordEncoder()
				.username("user1")
				.password("password")
				.roles("USER")
				.build();
		return new InMemoryUserDetailsManager(user);
	}
	// @formatter:on

	@Bean
	public PersistentTokenRepository persistentTokenRepository(DataSource dataSource) {
		JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
		jdbcTokenRepository.setDataSource(dataSource);
		return jdbcTokenRepository;
	}

	public LoginPwdDaoAuthenticationProvider loginPwdDaoAuthenticationProvider() {
		LoginPwdDaoAuthenticationProvider loginPwdDaoAuthenticationProvider = new LoginPwdDaoAuthenticationProvider();
		loginPwdDaoAuthenticationProvider.setUserDetailsService(userDetailsService());
		return loginPwdDaoAuthenticationProvider;
	}

	@Bean
	AuthenticationFailureHandler authenticationFailureHandler() {
		CustomAuthenticationFailureHandler customAuthenticationFailureHandler = new CustomAuthenticationFailureHandler();
		customAuthenticationFailureHandler.setDefaultFailureUrl("/login");
		return customAuthenticationFailureHandler;
	}

	private LogoutSuccessHandler logoutSuccessHandler() {
		return (request, response, authentication) -> {
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			APIResponse apiResponse = new APIResponse("0000","success");
			PrintWriter writer = response.getWriter();
			writer.write(JSONObject.toJSONString(apiResponse));
			writer.flush();
			writer.close();
		};
	}
}
